package com.example.myapplication.algorithm;

import java.util.ArrayList;
import java.util.List;

public class algorithm1 {
    public static double minPeakDistance = 75;
    public static double maxPeakDistance = 385;
    public static double minPeakHeight   = 20;

    public static double rri_avg = 0;
    public static List<Integer> RRI = new ArrayList<Integer>();
    public static int hr = 0;
    // //参数：数组，数组大小
    public static List<Integer> findPeaks(double[] num, int count, double minPeakDistance, double minPeakHeight) {
        List<Integer> sign = new ArrayList<Integer>();
        for (int i = 1; i < count; i++) {
            /* 相邻值做差： *小于0，，赋-1 *大于0，赋1 *等于0，赋0 */
            double diff = num[i] - num[i - 1];
            if (diff > 0) {
                sign.add(1);
            } else if (diff < 0) {
                sign.add(-1);
            } else {
                sign.add(0);
            }
        }
        // 再对sign相邻位做差
        // 保存极大值和极小值的位置
        List<Integer> indMax = new ArrayList<Integer>();
        List<Integer> indMin = new ArrayList<Integer>();
        List<Integer> rri_temp = new ArrayList<Integer>();
        RRI.clear();
        hr = 0;
        int peak_poss      = 0;
        int peak_poss_last = 0;
        int peak_cnt = 0;
        for (int j = 1; j < sign.size(); j++) {
            int diff = sign.get(j) - sign.get(j - 1);
            if (diff < 0) {
                if(peak_cnt == 0)//发现第一个波峰
                {
                    if(num[j]>minPeakHeight)
                    {
                        indMax.add(j);
                        peak_cnt++;
                        peak_poss = j;
                        peak_poss_last = peak_poss;
                    }
                }
                else if(peak_cnt > 0)//不是第一个波峰，需要大于minPeakDistance
                {
                    peak_poss = j;
                    int distance = peak_poss-peak_poss_last;
                    if(distance>=minPeakDistance && num[j]>minPeakHeight)
                    {
                        rri_temp.add(distance);
                        indMax.add(j);
                        peak_cnt++;
                        peak_poss_last = peak_poss;
                    }
                }
            } else if (diff > 0) {
                indMin.add(j);
            }
        }

        rri_avg = 0;
        int cnt = 0;
        for (int m = 0; m < rri_temp.size(); m++) {
            if(rri_temp.get(m)<maxPeakDistance && rri_temp.get(m)>minPeakDistance)
            {
                rri_avg += rri_temp.get(m);
                RRI.add(rri_temp.get(m));
                cnt++;
            }
        }

        rri_avg = rri_avg/cnt;
        hr = (int) (242*60/rri_avg);

        return RRI;
    }
}
